package org.learn.java.xuelie;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import org.learn.java.entity.User;

public class MySerializable {
	private static MySerializable demo = new MySerializable();
	public static void main(String[] args) {
		demo.write();
		demo.read();
	}

	
	public void write(){
		String filePath = "D:/tools/Git/wks/learn/user.txt";
		User user = new User();
		
		user.setId(new Long(1));
		user.setName("xiaoming");
		user.setAge(24);
		user.setSex("男");
		
		this.doWrite(user, filePath);
	}
	
	public void read(){
		String filePath = "D:/tools/Git/wks/learn/user.txt";
		User user =null;
		user = (User) doRead( filePath);
		user.print();
	}
	
	/**
	 * 对象序列化保存到文件
	 */
	@SuppressWarnings("resource")
	public void doWrite(Object obj,String filePath){
		try {
			ObjectOutput out = new ObjectOutputStream(new FileOutputStream(filePath));
			out.writeObject(obj);
			
		}catch (Exception e) {
			System.out.println("----对象保存异常----");
			e.printStackTrace();
		}
	}
	 
	/**
	 * 从文件中读取保存的对象
	 * @param filePath
	 * @return
	 */
	public Object doRead(String filePath){
		Object obj=null;
		try {
			ObjectInput in =new ObjectInputStream(new FileInputStream(filePath));
			obj = in.readObject();
		}catch (Exception e) {
			System.out.println("----对象读取异常----");
			e.printStackTrace();
		}
		return obj;
	}
}
